<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/6/7
 * Time: 14:38
 * 原始视频混音
 */
require_once dirname(__DIR__)."/common.php";
use app\cls\tom\Lock;
use app\cls\tom\FFmpeg;
use app\lib\db\DbException;
use app\cls\tom\SysResource;
use app\cls\tom\Process;
use app\cls\tom\Tools;
use app\model\Video;

$process = new Process(__FILE__);
$process->setProcessNum(4);
$process->initProcess();
$process->isTryError = false;
$redis = SysResource::getRedis();
$db =  SysResource::getDB(true);
$ffmpeg = new FFmpeg(false);
/*===============
 *初始化模型
 ================*/
$videoModel = new Video($db);
$cosUploadConfig = \app\cls\tom\Config::load("cos_upload");
$lock = new Lock("ori_material_audio_video_transcode_mix");
while(true){
    try{
        $readyList = $videoModel->getReadyHandleVideoMusic(10);
//        var_dump($readyList);exit;
        foreach($readyList as &$row){
//            var_dump($lock->unLock($row["id"]));continue;
//            $lockStatus = $lock->tryLock($row["video_id"]);
            if($lockStatus=true){
                //创建上传目录，配置上传
                $date1=date("Y",time());
                $date2=date("m",time());
                $date3=date("d",time());
                $dir=$date1."/".$date2."/".$date3;
                $oriVideoUrl = $row["video_url"];
                $noAudioVideo = $row["video_no_music_url"];
                $noAudioZimuVideo = $row["no_music_zimu_video"];
                //1.裁剪音频
                $totalStatus = [];
                if(empty($row["cut_music_url"])){
                    $oriMusicUrl = $row["video_music_url"];
                    $videoTime = $row["video_time"];
                    if(empty($videoTime)){
                        $videoTime = $ffmpeg->getVideoLen($oriVideoUrl);
                    }
                    $audioTime = $row["music_time"];
                    if(empty($audioTime)){
                        $audioTime = $ffmpeg->getVideoLen($oriMusicUrl);
                    }
                    if($audioTime>$videoTime){
                        $tempPath = CDN_PATH."/cut_audio/".$dir."/";
                        $cutAudios = $ffmpeg->cutVideo($oriMusicUrl,$tempPath,[["start"=>"00:00:00","duration"=>$ffmpeg->formatFFmpegTime($videoTime)]]);
                        if(empty($cutAudios)){
                            Tools::writeLog(["msg"=>"原始素材音视频混音失败","detail"=>["media_id"=>$row["video_id"],"msg"=>$ffmpeg->getLastError()],"ori_mix"]);
                            $db->update("video_transcode",["transcode_status"=>1,"transcode_msg"=>$ffmpeg->getLastError(),"transcode_count"=>"!transcode_count+1"],["video_id"=>$row["video_id"]]);
                            $lock->unLock($row["video_id"]);
                            continue;
                        }
                        $musicUrl = str_replace(CDN_PATH,CDN_HOST,$cutAudios[0]);
                    }else{
                        $musicUrl = $oriMusicUrl;
                    }
                    $audioPath = str_replace(CDN_HOST,CDN_PATH,$musicUrl);
                    $db->update("video_transcode",["cut_music_url"=>$musicUrl],["video_id"=>$row["video_id"]]);
                    $totalStatus[] = 1;
                }else{
                    $audioPath = str_replace(CDN_HOST,CDN_PATH,$row["cut_music_url"]);
                    $totalStatus[] = 1;
                }
                //2.有音频视频转码
                if(empty($row["transcode_video_url"])){
                    $outPutPath1 = CDN_PATH."/transCodeV1/".$dir."/".pathinfo($oriVideoUrl,PATHINFO_BASENAME);
                    $outPutPath11 = CDN_PATH."/lastCodeV1/".$dir."/".pathinfo($oriVideoUrl,PATHINFO_BASENAME);
                    $oriVideoPath = str_replace(CDN_HOST,CDN_PATH,$oriVideoUrl);
                    $re = $ffmpeg->transCode($oriVideoPath,$outPutPath1,$outPutPath11);
//                    $re = $ffmpeg->transCode($oriVideoPath,$outPutPath1);
//                    var_dump($re);exit;
                    if(!$re){
                        Tools::writeLog(["msg"=>"有音频视频转码失败","detail"=>["media_id"=>$row["video_id"],"msg"=>$ffmpeg->getLastError()],"ori_mix"]);
                        $db->update("video_transcode",["transcode_status"=>1,"transcode_msg"=>$ffmpeg->getLastError(),"transcode_count"=>"!transcode_count+1"],["video_id"=>$row["video_id"]]);
                        $lock->unLock($row["video_id"]);
                        continue;
                    }
                    $gaibian_video=str_replace(CDN_PATH,CDN_HOST,$outPutPath11);
                    $db->reconnect();
                    $db->update("video_transcode",["transcode_video_url"=>$gaibian_video],["video_id"=>$row["video_id"]]);
                    $totalStatus[] = 1;
                }else{
                    $totalStatus[] = 1;
                }
                //3.无音频视频转码
                if(empty($row["transcode_video_no_music_url"])){
                    $noAudioOutPutPath1 = CDN_PATH."/transCodeV2/".$dir."/".pathinfo($noAudioVideo,PATHINFO_BASENAME);
                    $noAudioOutPutPath11 = CDN_PATH."/lastCodeV2/".$dir."/".pathinfo($noAudioVideo,PATHINFO_BASENAME);
                    $noAudioOriVideoPath = str_replace(CDN_HOST,CDN_PATH,$noAudioVideo);
                    $re = $ffmpeg->transCode($noAudioOriVideoPath,$noAudioOutPutPath1,$noAudioOutPutPath11);
//                    $re = $ffmpeg->transCode($noAudioOriVideoPath,$noAudioOutPutPath1);
                    if(!$re){
                        Tools::writeLog(["msg"=>"无音频视频转码失败","detail"=>["media_id"=>$row["video_id"],"msg"=>$ffmpeg->getLastError()],"ori_mix"]);
                        $db->update("video_transcode",["transcode_status"=>1,"transcode_msg"=>$ffmpeg->getLastError(),"transcode_count"=>"!transcode_count+1"],["video_id"=>$row["video_id"]]);
                        $lock->unLock($row["video_id"]);
                        continue;
                    }
                    $db->reconnect();
                    $db->update("video_transcode",["transcode_video_no_music_url"=>str_replace(CDN_PATH,CDN_HOST,$noAudioOutPutPath11)],["video_id"=>$row["video_id"]]);
                    $totalStatus[] = 1;
                }else{
                    $totalStatus[] = 1;
                }
                //4.无音频无字幕视频转码
                if(empty($row["transcode_no_music_zimu_video"])){
//                    var_dump(147);exit;
                    $noAudioZimuVideoPath4= CDN_PATH."/transCodeV4/".$dir."/".pathinfo($noAudioZimuVideo,PATHINFO_BASENAME);
                    $noAudioZimuVideoPath44 = CDN_PATH."/lastCodeV4/".$dir."/".pathinfo($noAudioVideo,PATHINFO_BASENAME);
                    $noAudioZimuVideoPath = str_replace(CDN_HOST,CDN_PATH,$noAudioZimuVideo);
                    $re = $ffmpeg->transCode($noAudioZimuVideoPath,$noAudioZimuVideoPath4,$noAudioZimuVideoPath44);
                    if(!$re){
                        Tools::writeLog(["msg"=>"无音频无字幕视频转码","detail"=>["media_id"=>$row["video_id"],"msg"=>$ffmpeg->getLastError()],"ori_mix"]);
                        $db->update("video",["transcode_status"=>1,"transcode_msg"=>$ffmpeg->getLastError(),"transcode_count"=>"!transcode_count+1"],["video_id"=>$row["video_id"]]);
                        $lock->unLock($row["video_id"]);
                        continue;
                    }
                    $db->reconnect();
                    $db->update("video",["transcode_no_music_zimu_video"=>str_replace(CDN_PATH,CDN_HOST,$noAudioZimuVideoPath4)],["video_id"=>$row["video_id"]]);
                    $totalStatus[] = 1;
                }else{
                    $totalStatus[] = 1;
                }
                //5.获取视频的宽高
                if(empty($row["width"]) || empty($row["height"])){
                    if(empty($row['transcode_video_url'])){
                        $re1=$ffmpeg->getVideoDetail($gaibian_video);
                    }else{
                        $re1=$ffmpeg->getVideoDetail($row['transcode_video_url']);
                    }
//                    var_dump($re1);exit;
                    if(empty($re1)){
                        Tools::writeLog(["msg"=>"修改视频宽高失败","detail"=>["media_id"=>$row["video_id"],"msg"=>$ffmpeg->getLastError()],"ori_mix"]);
                        $db->update("video_transcode",["transcode_status"=>1,"transcode_msg"=>$ffmpeg->getLastError(),"transcode_count"=>"!transcode_count+1"],["video_id"=>$row["video_id"]]);
                        $lock->unLock($row["video_id"]);
                        continue;
                    }
                    $db->reconnect();
                    $db->update("video_transcode",["width"=>$re1['width'],"height"=>$re1['height']],["video_id"=>$row["video_id"]]);
                    $totalStatus[] = 1;
                }else{
                    $totalStatus[] = 1;
                }
                if(count($totalStatus) == 5){
                    $db->update("video_transcode",["transcode_status"=>2,"transcode_msg"=>"转码成功","transcode_count"=>"!transcode_count+1"],["video_id"=>$row["video_id"]]);
                }
                $lock->unLock($row["video_id"]);
            }
        }
    }catch (DBException $e){
        echo $e->getMessage();
//        $process->restartProcess();
    }catch (RedisException $e){

    }catch (Exception $e){
        if(!empty($row)){
            $db->update("video_transcode",["transcode_status"=>1,"transcode_msg"=>$e->getMessage(),"transcode_count"=>"!transcode_count+1"],["video_id"=>$row["video_id"]]);
            $lock->unLock($row["video_id"]);
        }
        Tools::writeLog(["msg"=>"音视频混音失败","detail"=>["msg"=>$e->getMessage(),"video_id"=>$id],"mix"]);
    }
    sleep(2);
    $process->checkProcessTime(true);
    $db->reconnect();
}


